package com.chat.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chat.admin.mapper.FileMapMapper;
import com.chat.admin.service.IFileMapService;
import com.chat.admin.utils.FileUploadUtil;
import com.chat.common.common.exception.RoutineException;
import com.chat.common.entity.DisableAccount;
import com.chat.common.entity.FileMap;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author weikjie
 * @since 2024-05-23
 */
@Service
@Slf4j
public class FileMapServiceImpl extends ServiceImpl<FileMapMapper, FileMap> implements IFileMapService {

    @Autowired
    FileUploadUtil fileUploadUtil;

    @Override
    public String UpdateFileMap(MultipartFile file, String[] pathSegments) throws IOException {
        FileMap fileMap;
        try {
            fileMap = fileUploadUtil.uploadFile(file, pathSegments);
        } catch (IOException e) {
            e.printStackTrace();
            throw new IOException("文件上传失败", e);
        }
        try {
            baseMapper.insert(fileMap);
        } catch (DataAccessException e) {
            // 如果发生SQL异常，删除文件
            log.info(e.getMessage());
            assert fileMap != null;
            try {
                fileUploadUtil.deleteFile(fileMap.getFilePath());
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            throw new RoutineException("数据库插入失败");
        }
        return fileMap.getFileId();
    }


    @Override
    public int deleteByPath(String filePath) {
        try {
            fileUploadUtil.deleteFile(filePath);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        QueryWrapper<FileMap> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("file_path",filePath);
        return baseMapper.delete(queryWrapper);
    }

    @Override
    public String getFilePathByID(String fileID) {
        QueryWrapper<FileMap> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("file_id",fileID);
        FileMap fileMap = baseMapper.selectOne(queryWrapper);
        return fileMap.getFilePath();
    }
}
